﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.BizExtensions;
using User.Api.Dto.Ward;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace User.Api.Controllers
{
    public class WardController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(WardController));
        private FsssdqfybjyEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new FsssdqfybjyEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取用户的所有住院号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetAll")]
        public GetAllResponse GetAll()
        {
            var azUser = AzUser.GetInApi(Request);
            //之前的查询会发生死锁，优化查询为NoLock
            var dbWards = (_ctx.HospWardPatients.Where(x => x.WxUserId == azUser.UserId && x.RecStatus == 1)
                .OrderByDescending(x => x.IsDefault).ThenBy(x => x.WardNo)
                .Select(x => new
                {
                    Id = x.Id,
                    x.WardNo,
                    x.Name,
                    x.IsDefault
                })).ToListReadUncommitted();

            var wards = dbWards.Select(x => new GetAllResponse.Ward
            {
                Id = x.Id,
                Num = x.WardNo,
                Name = x.Name,
                IsDefault = x.IsDefault == 1
            }).ToList();

            return new GetAllResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Wards = wards
            };
        }

        /// <summary>
        /// 设置默认住院号
        /// </summary>
        /// <param name="id">住院号id</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("SetDefault")]
        public SetDefaultResponse SetDefault(long id)
        {
            var azUser = AzUser.GetInApi(Request);

            var wards = _ctx.HospWardPatients.Where(x => x.WxUserId == azUser.UserId).ToList();
            foreach (var ward in wards)
            {
                ward.IsDefault = 0;
                if (ward.Id == id)
                {
                    ward.IsDefault = 1;
                }
            }
            _ctx.SaveChanges();

            return new SetDefaultResponse { ResultCode = "0", ResultMsg = "" };
        }

        /// <summary>
        /// 删除住院号
        /// </summary>
        /// <param name="id">住院号id</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("Delete")]
        public DeleteResponse Delete(int id)
        {
            var azUser = AzUser.GetInApi(Request);

            var ward = _ctx.HospWardPatients.FirstOrDefault(x => x.Id == id && x.WxUserId == azUser.UserId);
            if (ward != null)
            {
                ward.RecStatus = 2;
                ward.RecDeleteDt = DateTime.Now;
                _ctx.SaveChanges();

                // 如果删除了默认卡，则自动设置其余住院号小的卡为默认住院号
                if (ward.IsDefault == 1)
                {
                    var wards = _ctx.HospWardPatients.Where(x => x.RecStatus == 1 && x.WxUserId == azUser.UserId)
                        .OrderBy(x => x.WardNo).ToList();
                    for (int i = 0; i < wards.Count; i++)
                    {
                        wards[i].IsDefault = i == 0 ? 1 : 0;
                    }
                    _ctx.SaveChanges();
                }
            }

            return new DeleteResponse { ResultCode = "0", ResultMsg = "" };
        }

        /// <summary>
        /// 绑定住院号
        /// </summary>
        /// <param name="isDefault">是否设置为默认住院号</param>
        /// <param name="num">住院号</param>
        /// <param name="name">姓名</param>
        /// <param name="idNo">身份证号</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("AddBinding")]
        public AddBindingResponse AddBinding(bool isDefault, string num, string name, string idNo)
        {
            var azUser = AzUser.GetInApi(Request);

            var wardMax = ConfigurationManager.AppSettings["WardMax"].ToInt32();
            var wardCount = _ctx.HospWardPatients
                .Count(x => x.WxUserId == azUser.UserId && x.RecStatus == 1);
            if (wardCount >= wardMax)
            {
                return new AddBindingResponse
                {
                    ResultCode = "1",
                    ResultMsg = "最多可以添加" + wardMax + "个住院号!"
                };
            }

            if (wardCount == 0)
            {
                isDefault = true;
            }

            var existWard =
                _ctx.HospWardPatients.FirstOrDefault(x => x.RecStatus == 1 && x.WardNo == num && x.WxUserId == azUser.UserId);
            if (existWard != null)
            {
                return new AddBindingResponse
                {
                    ResultCode = "2",
                    ResultMsg = "您已添加过该住院号!"
                };
            }

            // 获取院内住院号信息
            var request = new Request4GetWardPatient();
            request.WardNo = num;
            request.IdCard = idNo;

            Response4GetWardPatient response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetWardPatient", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<Response4GetWardPatient>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new AddBindingResponse
                {
                    ResultCode = "3",
                    ResultMsg = "操作失败，获取住院号信息超时"
                };
            }

            if (response.ResultCode != "0")
            {
                return new AddBindingResponse
                {
                    ResultCode = "4",
                    ResultMsg = response.ResultDesc
                };
            }

            if (string.IsNullOrEmpty(response.WardPatientInfo.Name))
            {
                return new AddBindingResponse
                {
                    ResultCode = "2",
                    ResultMsg = "住院号或身份证号输入错误"
                };
            }

            if (response.WardPatientInfo.Name.Trim() != name.Trim())
            {
                return new AddBindingResponse
                {
                    ResultCode = "2",
                    ResultMsg = "操作失败，住院号与姓名不匹配"
                };
            }

            var patientInfo = response.WardPatientInfo;

            var newWardPatient = new HospWardPatient
            {
                WxUserId = azUser.UserId,
                WardNo = patientInfo.WardNo,
                PatientName = patientInfo.Name.Trim(),
                RecStatus = 1,
                RecCreateDt = DateTime.Now,
                RecUpdateDt = DateTime.Now,
                PatientId = patientInfo.HosPatId.Trim(),
                Name = patientInfo.Name.Trim(),
                Gender = patientInfo.Sex.Trim(),
                //Age = patientInfo.Age.Trim(),
                Birthdate = patientInfo.BirthDay.Trim(),
                IdenNo = patientInfo.IdCard.Trim(),
                Phone = patientInfo.Phone.Trim(),
                FeeType = patientInfo.PayType.Trim()
            };

            _ctx.HospWardPatients.Add(newWardPatient);
            _ctx.SaveChanges();

            var existsWardPatients = _ctx.HospWardPatients.Where(x => x.WardNo == newWardPatient.WardNo);
            foreach (var existsWardPatient in existsWardPatients)
            {
                existsWardPatient.RecUpdateDt = DateTime.Now;
                existsWardPatient.PatientName = newWardPatient.PatientName;
                existsWardPatient.PatientId = newWardPatient.PatientId;
                existsWardPatient.Name = newWardPatient.Name;
                existsWardPatient.Gender = newWardPatient.Gender;
                existsWardPatient.Age = newWardPatient.Age;
                existsWardPatient.Birthdate = newWardPatient.Birthdate;
                existsWardPatient.IdenNo = newWardPatient.IdenNo;
                existsWardPatient.Phone = newWardPatient.Phone;
                existsWardPatient.FeeType = newWardPatient.FeeType;
            }
            _ctx.SaveChanges();

            if (isDefault)
            {
                SetDefault(newWardPatient.Id);
            }

            return new AddBindingResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Id = newWardPatient.Id,
                Num = newWardPatient.WardNo,
                Name = newWardPatient.PatientName,
                IsDefault = newWardPatient.IsDefault == 1,
                IsSelected = false
            };
        }
    }
}
